/*
 * @lc app=leetcode.cn id=1319 lang=typescript
 *
 * [1319] 连通网络的操作次数
 */

// @lc code=start
class UnionFind {
  parent: number[];
  size: number[];
  count: number;
  constructor(n: number = 0) {
    this.parent = new Array(n).fill(0).map((_, i) => i);
    this.size = new Array(n).fill(1);
    this.count = n;
  }
  find(x: number): number {
    return this.parent[x] === x ? x : (this.parent[x] = this.find(this.parent[x]));
  }
  union(x: number, y: number): void {
    let rx = this.find(x);
    let ry = this.find(y);
    if (rx === ry) return;
    if (this.size[rx] > this.size[ry]) {
      [rx, ry] = [ry, rx];
    }
    this.size[ry] += this.size[rx];
    this.parent[rx] = ry;
    this.count--;
  }
}

function makeConnected(n: number, connections: number[][]): number {
  const size = connections.length;
  if (size < n - 1) return -1;

  const unionFind = new UnionFind(n);
  for (const [x, y] of connections) {
    unionFind.union(x, y);
  }

  return unionFind.count - 1;
}
// @lc code=end
